package com.example.design.leetcode.other;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description TODO
 * @date 2023/5/16 8:47
 * @Author liuzhihui
 * @Version 1.0
 */
public class Lru2 {
    int cap;
    Map<Integer, Integer> cache = new LinkedHashMap<>();

    public Lru2(int cap) {
        this.cap = cap;
    }

    public int get(int key) {
        // todo 忘记
        if (!cache.containsKey(key)) {
            return -1;
        }

        makeRecently(key);
        return cache.get(key);
    }

    public void put(int key, int val) {
        if (cache.containsKey(key)) {
            makeRecently(key);
            cache.put(key,val);
            // todo 忘记
            return;
        }

        if (cache.size() >= cap) {
            Integer oldestKey = cache.keySet().iterator().next();
            cache.remove(oldestKey);
        }

        cache.put(key, val);
    }

    private void makeRecently(int key) {
        Integer val = cache.get(key);
        cache.remove(key);
        cache.put(key, val);
    }
}
